// pages/patrolLog/patrolLog.js  
const app = getApp()
const util = require('../../../utils/util.js')
var BLELocker = require("../../../utils/BLELocker.js")
var blueConStatHandler = require("../../../utils/blueConStatHandler.js")
var Base64 = require('../../../utils/base64.js')
const lbbService = require('../../service/service.js')

Page({
  data: {
    requestFlag: false,
    rfidCode: '',
    firstShow:true,
    equipCode: '',
    pileCode: '',
    hospitalId: '',
    equipTypeIndex: 0,
    equipTypeArray: ['轮椅', '担架'],
    show:true,
    selGoodsList:[],
    myPartList:[],
    batteryType: 1,
    myPartList: [],
    pileBtns: ['changeLocation', 'changeBrCode', 'offLine', 'maintain', 'changeBtr', 'changeParts', 'changeBox', 'updateCard', 'rfidErr', 'statusDetail','lostChair','rentInfo','insertSwitch','hookSwitch','searchTimeout'],
    equipBtns: ['changeLocation', 'offLine', 'changeParts', 'maintain', 'changeRfid', 'noReturn', 'confirmLost', 'rentList', 'visitList', 'monthRent'],
  },

  onLoad: function(options) {
    let that = this;
    console.log(options.hospitalId,'hospitalIdhospitalId')
    that.setData({
      pileCode: options.pileCode.replace(/[^0-9]/ig, ""),
      macId: options.macId || '',
      wxDeviceId: getApp().getDeviceId(options.macId),
      pileType: options.pileType,
      hospitalId: options.hospitalId,
      newConFlg: options.newConFlg == 'true' ? true : options.newConFlg == 'false'?false:null,
      scrollHeight:app.getScrollHeight(0),
    });
    if(that.data.newConFlg === true || that.data.newConFlg === false){
      that.getConnected(that.data.macId, that.openLock);
    }
    // if (that.data.newConFlg === true || that.data.newConFlg === false) {
    //   that.getConnect(that.data.macId);
    // } else {
    //   that.getPileInfo(that.data.pileCode);
    // }
  },

  onReady: function() {
    let that = this
    that.toast = that.selectComponent("#toast")
    that.personalModal = that.selectComponent("#personalModal")
  },
  /*开锁*/
  openLock() {
    let that = this;
    console.log('BBBox',that.data.data_95)
    if (that.data.data_95) {
      that.setData({
        loading_desc:'正在开锁...'
      })
      lbbService.openLock({
        rfId: that.data.data_95.rfid,
        mac: that.data.macId,
        costTime: that.data.data_95.costTime,
        //insertSwitch: that.data.data_95.
      },function(res){
        BLELocker.send85Command(function (isSuccess) {
          
          if (isSuccess == false) {
            that.setData({
              loading_show: false,
            });
            wx.showToast({
              title: '开锁失败请重试',
              image:'/images/gantan.png',
              duration:2000
            })
          } else {
            that.uploadAndGet()
            setTimeout(() => {
              that.setData({
                loading_show: false,
              });
            },4000)
          }
        });
      })
    } else {
      wx.showToast({
        title: '连接失败请重试',
        image: '/images/gantan.png'
      })
    }
  },
  getConnected: function (macId, _callback) {
    let that = this;
    that.setData({
      loading_show:true,
      loading_desc:'设备连接中...'
    })
    if (that.data.newConFlg) {
      BLELocker.newConnect('DK' + macId, function (status, data) {
        blueConStatHandler.handleStatus(status, data, that, _callback, true)
      }, 0, false, null, null, that);
    } else {
      BLELocker.directConnect('DK' + macId, function (status, data) {
        blueConStatHandler.handleStatus(status, data, that, _callback, true)
      }, 0, false, null, null, that);
    };
  },
  onShow: function() {
    let that = this;
    //添加物品
    if (that.data.addGoodsFlag) {
      let list = that.data.selGoodsList
      that.setData({
        show: false,
      })
      util.print('selGoodsList',list);
      for (var i = 0; i < list.length; i++) {
        that.selGoodsAdd(list[i]);
      }
      that.data.selGoodsList = [];
      that.setData({
        show: true,
      })
    }
  },

  /**
   * 图片预览
   */
  preViewImgs:function(e){
    let current = e.currentTarget.dataset.current;
    let urls = e.currentTarget.dataset.urls;
    util.previewImgs(current,urls);
  },

  getConnect: function (mac_id) {
    let macId = mac_id || that.data.macId
    let that = this
    that.setData({
      loading_show: true,
      loading_desc: '设备连接中...'
    })
    if (that.data.newConFlg) {
      BLELocker.newConnect('DK' + macId, function (status, data) {
        blueConStatHandler.handleStatus(status, data, that, that.uploadAndGet, true)
      }, 0, false, null, null, that);
    } else {
      BLELocker.directConnect('DK' + macId, function (status, data) {
        blueConStatHandler.handleStatus(status, data, that, that.uploadAndGet, true)
      }, 0, false, null, null, that);
    };
  },
  uploadAndGet: function() {
    let that = this
    that.setData({
      requestFlag: false,
      retryBtnShow: false
    })
    if (that.data.data_95) {
      that.data.rfid = that.data.data_95.rfid;
      lbbService.getPileDetailInfo({
        hid: parseInt(that.data.pileCode),
        rfid: that.data.rfid,
      }, function(res) {
        that.setData({
          pileInfo: res,
          loading_show: false,
        })
        if (res.equipInfo && res.equipInfo.equipCode){
          that.setData({
            equipCode: res.equipInfo.equipCode
          })
        }
        if (that.data.pileChecking) {
          that.data.pileChecking = false;
          that.completePileCheckCallBack();
        }
      })
    } else {
      that.setData({
        loading_show: false,
      })
      wx.showToast({
        title: '读取失败请重试',
        image: '/images/gantan.png',
        duration: 2500
      })
    }
  },
  hideModal1() {
    this.setData({
      modal: {
        modal_show: false,
        confirm: false,
        retry95: false,
        retryConnect: false
      }
    })
  },
  /**
   * 重试95
   */ 
  retry95() {
    let that = this;
    that.hideModal1();
    that.setData({
      loading_show: true,
      loading_desc: "数据读取中"
    });
    BLELocker.send95Command(function (isSuccess) {
      if (isSuccess == false) {
        that.getConnect(that.data.macId);
      } else {
        that.uploadAndGet();
      }
    })
  },
  /**
   * 重试蓝牙连接
   */
  retryConnect() {
    let that = this;
    that.hideModal1();
    that.setData({
      loading_show: true,
      loading_desc: "设备连接中"
    });
    that.getConnect(that.data.macId);
  },
  getLocation: function() {
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log('获取经纬度成功', res)
        app.globalData.header.lat = parseFloat(res.latitude)
        app.globalData.header.lng = parseFloat(res.longitude)
      },
      fail: function(res) {
        console.log('获取经纬度fail', res)
      }
    })
  },
  stopMaoPao: function(e) {
    return
  },
  completePileCheck: function() {
    let that = this
    // 这里完成检查，将表单提交，并将桩位的巡检状态写为已巡检，然后返回上一层页面
    that.data.pileChecking = true;
    if (that.data.rfid) {
      that.retry95()
    }
  },
  completePileCheckCallBack: function() {
    let that = this
    lbbService.completeCheck({
        hid: parseInt(that.data.pileCode),
        hospitalId: parseInt(that.data.hospitalId)
      },function(res){
        if (res.result == 0) {
          that.getLocation()
          wx.showToast({
            title: '完成检查',
            duration: 2000
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 2000)
        } else {
          that.setData({
            modal:{
              modal_show:true,
              desc: '提交失败：' + res.result + res.description,
              confirm:true
            }
          })
        }
      })
  },
  
  //完成检查前的表单校验
  formCheck: function() {
    let that = this
    if (that.data.pileInfo.lowPower) {
      that.toast.showToast('请充电，或更换电池')
      return false
    } else if (that.data.pileInfo.maintaining) {
      that.toast.showToast('请维修完成后再提交')
      return false
    } else if (that.data.pileInfo.allopatric || that.data.pileInfo.equipInfo.allopatric) {
      that.toast.showToast('请处理异地归还设备')
      return false
    } else if (that.data.pileInfo.equipInfo.faultCode == '可能丢失') {
      that.toast.showToast('请确认设备是否丢失或RFID不识别')
      return false
    } else if (that.data.pileInfo.equipInfo.faultCode == '未归还') {
      that.toast.showToast('请处理未归还的设备')
      return false
    }
    for (let i = 0; i < that.data.pileInfo.mayLostEquipList.length; i++) {
      if (that.data.pileInfo.mayLostEquipList[i].faultCode == '可能丢失') {
        that.toast.showToast('请确认设备' + that.data.pileInfo.mayLostEquipList[i].equipCode + '是否丢失或RFID不识别')
        return false
      }
    }
    return true
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      partList:[]
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    BLELocker.disconnect();
  },

  /**
   * 获取设备详情
   */
  getEquipInfo: function () {
    let that = this
    let equipCode = that.data.pileInfo.equipInfo.equipCode.replace(/[^0-9]/ig, "")
    lbbService.getEquipDetailInfo({
      equId: parseInt(equipCode)
    }, function (res) {
      that.setData({
        equipInfo: res.data,
      })
    })
  },
  selGoodsAdd: function (selectGoods) {
    let index = this.data.myPartList.findIndex(item=>item.id==selectGoods.id);
    if(index>-1){
      this.data.myPartList[index].accNum = selectGoods.accNum;
    } else {
      this.data.myPartList.push(selectGoods);
    }
    this.setData({
      myPartList: this.data.myPartList
    });
    this.data.addGoodsFlag = false;
  },
  /**
   * 清除已选择的配件
   */
  deleteMyPartList: function(){
    this.setData({
      myPartList:[]
    })
  },
  deleteParts: function (e) {
    let that = this;
    let id = e.detail;
    console.log('deleteParts', id);
    let myPartList = that.data.myPartList;
    myPartList.forEach((item, index) => {
      if (item.id == id) {
        myPartList.splice(index, 1);
      }
    })
    that.setData({
      myPartList: myPartList
    })
  },
  /**
   * 获取桩信息
   */
  getPileInfo: function () {
    let that = this
    let pileCode = that.data.pileCode;
    lbbService.getPileDetailInfo({
      hid: parseInt(pileCode)
    }, function (res) {
      that.setData({
        pileInfo: res,
        equipCode:res.equipInfo&&res.equipInfo.equipCode?res.equipInfo.equipCode.replace(/[^0-9]/ig, ""):'',
        equipInfo:res.equipInfo&&res.equipInfo.equipCode?res.equipInfo:'',
      })
    })
  },
  feedback(){
    console.log('巡检反馈')
  },
  scanBack(){
    console.log('归还')
  }
})